﻿using AutoMapper;
using BusinessInterface;
using Common;
using Common.EnumEntity;
using Common.Result;
using ModelDtos.User;
using Models.Entity;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessService
{
    public class UserManagerService : BaseService, IUserManagerService
    {
        private readonly IMapper _IMapper;

        public UserManagerService(ISqlSugarClient client, IMapper mapper) : base(client)
        {
            _IMapper = mapper;
        }

        /// <summary>
        /// 注册用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public ApiResult Register(Sys_User user)
        {
            user.Password = MD5Encrypt.Encrypt(user.Password!);
            Sys_User uResult = Insert(user);
            return new ApiResult()
            {
                Success = true,
                Message = "注册成功"
            };
        }

        /// <summary>
        /// 登录成功查询到的用户信息
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public SysUserInfo? Login(string userName, string password)
        {
            string pwd = MD5Encrypt.Encrypt(password);

            List<Sys_User> userList = _Client
                  .Queryable<Sys_User>()
                  .Where(c => c.Name.Equals(userName) && c.Password.Equals(pwd))
                  .ToList();
            if (userList == null || userList.Count <= 0)
            {
                return null;
            }
            Sys_User user = userList.First();
            SysUserInfo userinfo = _IMapper.Map<Sys_User, SysUserInfo>(user);

         

            user.LastLoginTime = DateTime.Now;
            _Client.Updateable(user).ExecuteCommand();

            return userinfo;
        }

     
    }
}
